package com.example.shuimu;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.nfc.cardemulation.HostNfcFService;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteMaskRegisterRequest;
import com.serotonin.modbus4j.msg.WriteRegisterRequest;
import com.serotonin.modbus4j.serial.SerialPortWrapper;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class NoPlcActivity extends AppCompatActivity implements View.OnClickListener {
    SerialPortWrapper serialParameters;
    SerialPortWrapper serialParameters2; //第二路 modbus
    ModbusFactory modbusFactory;
    ModbusMaster master;
    ModbusFactory modbusFactory2;
    ModbusMaster master2;
    ProgressBar pb;

    private TextView tv_pinlv, tv_pm25, tv_shuiweibaohu;  //
    private TextView shuifa,tv_gaodu;  //
    private TextView kaiguang;  //
    private TextView tv_shuiwei;  //
    private TextView tv_shoudong;  //
    private TextView tv_air;  //
    private TextView tvMoshi;  //
    private TextView TvWndu, Tv_shidu, TV_p25, TV_p10, TV_zaosheng, tv_qiya, TV_fengsu;  //
    private ToggleButton toggleButton;
    private Button kongzhizidong1;  //
    private Button kongzhizidong2;  //
    private Button btn_pm25;  //


    private Button famen1;  //
    private Button famen2;  //

    private Button bnt_shenggao;  //
    private Button btn_xiajiang;  //
    private Button btn_xuanzhuan;  //

    private Button shuibeng1,btn_baohu;  //
    private Button shuibeng2;  //
    private Button btn_qiehuan3;  //

    private Button btn_sheweishoudong;  //
    private Button btn_sheweizidong;  //

    Timer timer = new Timer();
    TimerTask task;

    Timer NoticeTimer = new Timer(); //更新界面定时器
    TimerTask Noticetask;


    Timer LiganTimer = new Timer(); //立杆
    TimerTask Ligantask;

    //定时去看一下 定时器是否开机
    Timer timerDingshi = new Timer();
    TimerTask taskDingshi;
    int dianjishort = 0;   // 电机状态
    int famenshort = 0;    //阀门状态
    short kongzhimoshishort = 0; //控制模式
    short yewei = 0; //液位

    String url = "tcp://broker.emqx.io:1883";
    String user = "1553592282";
    String pass = "1553592282";
    String id = "mqttx_f0621e13";


    boolean shengaoflag = false;
    private ScheduledExecutorService scheduler;
    private MqttClient client;
    private Handler handler;
    //这些都写你自己的或者找个测试的地址
    private String host = "tcp://1.92.108.110:1883";     // TCP协议
    private String userName = "shuimu"; //mqtt用户名称
    private String passWord = "123";//mqtt用户密码

    private String mqtt_id = "mqttx_" + System.currentTimeMillis();//mqtt id
    private String mqtt_sub_topic = "set_penlin_status_gd2";//mqtt订阅的主题的标识
    private String mqtt_pub_topic = "get_penlin_status_gd2";//mqtt你发布的主题的标识
    private String mqtt_sub_topic2 = "bug";//mqtt订阅bug
    private boolean ligan = false;

    private long startTime = 0;
    private long endTime = 0;

    //开启和关闭的时间
    private long openTime = 0;
    private long closeTime = 0;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static MqttConnectOptions mMqttConnectOptions;
    MqttAndroidClient mqttAndroidClient = null;
    private String wendu, zaoseng, p25 = "0", p10, qiya, yeweishangchuan = "0";
    private String shidu, fengsu, shangshengStr = "0", xiajiangStr = "0", xuanzhuanStr = "0",gaodu="0";
    String pm25, baohuzhi = "0.3";
    String pinlv;
    float yeweiF;
    String moshi = "0";  //0是手动，1是自动，2是定时
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getSupportActionBar().hide();
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_no_plc);
        pb = findViewById(R.id.battery_pb);


        shuifa = findViewById(R.id.tv_famen);
        tvMoshi = findViewById(R.id.tv_moshi);
        kaiguang = findViewById(R.id.tv_shuibeng);
        tv_shuiwei = findViewById(R.id.tv_shuiwei);
        tv_pinlv = findViewById(R.id.tv_pinlv);
        tv_pm25 = findViewById(R.id.tv_pm25);
        tv_shuiweibaohu = findViewById(R.id.tv_shuiweibaohu);
        bnt_shenggao = findViewById(R.id.btn_shengao);
        btn_xiajiang = findViewById(R.id.btn_jiang);
        btn_baohu = findViewById(R.id.btn_baohu);
        // TvWndu,Tv_shidu,TV_p25,TV_p10,TV_zaosheng,tv_qiya,TV_fengsu;
        TvWndu = findViewById(R.id.tv_wen);
        Tv_shidu = findViewById(R.id.tv_shidu);
        TV_p25 = findViewById(R.id.tv_p25);
        TV_p10 = findViewById(R.id.tv_p10);
        TV_zaosheng = findViewById(R.id.tv_zaosheng);
        tv_qiya = findViewById(R.id.tv_qiya);
        TV_fengsu = findViewById(R.id.tv_fengsu);
        tv_gaodu = findViewById(R.id.tv_gaodu);


        toggleButton = findViewById(R.id.switch_button);

        famen1 = findViewById(R.id.btn_send1);
        famen2 = findViewById(R.id.btn_send2);
        shuibeng1 = findViewById(R.id.btn_shuibeng1);
        shuibeng2 = findViewById(R.id.btn_shuibeng2);
        btn_qiehuan3 = findViewById(R.id.btn_qiehuan3);
        btn_xuanzhuan = findViewById(R.id.btn_xuanzhuan);
        tv_air = findViewById(R.id.tv_air);


        btn_sheweishoudong = findViewById(R.id.btn_shoudong);
        btn_sheweizidong = findViewById(R.id.btn_zidong);
        btn_pm25 = findViewById(R.id.btn_pm25);

        if(shengaoflag){
            bnt_shenggao.setEnabled(false);bnt_shenggao.setBackgroundColor(Color.GRAY);
            btn_xiajiang.setEnabled(false);btn_xiajiang.setBackgroundColor(Color.GRAY);
            btn_xuanzhuan.setEnabled(false);btn_xuanzhuan.setBackgroundColor(Color.GRAY);
        }
//        kongzhizidong1.setOnClickListener(this);
//        kongzhizidong2.setOnClickListener(this);
        btn_pm25.setOnClickListener(this);
        famen1.setOnClickListener(this);
        famen2.setOnClickListener(this);
        shuibeng1.setOnClickListener(this);

        shuibeng2.setOnClickListener(this);
//        btn_qiehuan3.setOnClickListener(this);

        btn_sheweishoudong.setOnClickListener(this);
        btn_sheweizidong.setOnClickListener(this);
        btn_baohu.setOnClickListener(this);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    SpUtils.put(NoPlcActivity.this, "check", "t");
                } else {

                    SpUtils.put(NoPlcActivity.this, "check", "f");
                }

            }
        });
        String cstring = (String) SpUtils.get(NoPlcActivity.this, "check", "t");
        if (cstring.equals("t")) {
            toggleButton.setChecked(true);
        } else {
            toggleButton.setChecked(false);
        }

        initSirPort();

        task = new TimerTask() {
            @Override
            public void run() {
                // 执行某个任务

                PanDuanPm25();
                SendAir();

            }
        };
        timer.schedule(task, 5000, 3000);

        //定时 刷新UI
        Noticetask = new TimerTask() {
            @Override
            public void run() {
                GetInfo();

                getShuiwei();
            }
        };
        NoticeTimer.schedule(Noticetask, 5000, 3000);

        //立杆 刷新UI
        Ligantask = new TimerTask() {
            @Override
            public void run() {
                //sendMqtt(mqtt_pub_topic, "yanchen=" + (toggleButton.isChecked() ? "1" : "0"));

                if (true) {
                    //获取立杆状态
                    try {
                        ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 9, 1);
                        ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master2.send(request);

                        if (response.isException()) {
                            Log.e("SirPort1", "Exception response:_空气站" + response.getExceptionMessage());
                        } else {
                            short[] list = response.getShortData();
                            short getnum = list[0];
                            gaodu =""+ getnum;

                            double tt = ((double)getnum ) /100; //米
                            Log.d("tttt",getnum+"=="+tt);
                            sendMqtt(mqtt_pub_topic, "gaodu=" +   df.format(tt)+"米");
                        }


                        //new WriteMaskRegisterRequest()


                    } catch (Exception e) {
                        Log.e("Exception", e.getMessage());
                        try {
                            master2.init();
                        } catch (ModbusInitException modbusInitException) {
                            modbusInitException.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(NoPlcActivity.this, "获取立杆PLC失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        };

        LiganTimer.schedule(Ligantask, 5000, 1000);

        taskDingshi = new TimerTask() {
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis();

                if (!moshi.equals("2")) {
                    return;
                }
                if (timestamp > startTime && timestamp < endTime) {

                    long totleTime = openTime + closeTime;

                    int result = (int) ((endTime - startTime) / totleTime); // 结果是 3

                    if (timestamp > (totleTime * 0 + startTime) && timestamp < (startTime + totleTime * 0 + openTime)) {
                        Log.d("dingshiqi", "shuibengkai==" + timestamp + "==" + (totleTime * 0 + startTime) + "==" + (startTime + totleTime * 0 + openTime));
                        shuibeng1();
                    }
                    if (timestamp > (startTime + totleTime * 0 + openTime) && timestamp > (totleTime * 1 + startTime)) {
                        shuibeng2();
                        Log.d("dingshiqi", "shuibengguan==" + (startTime + totleTime * 0 + openTime) + "== " + (totleTime * 1 + startTime));
                    }


//                    if( timestamp> (totleTime*1 + startTime )  && timestamp < (startTime + totleTime*1 + openTime) ){
//                        Log.d("dingshiqi","shuibengkai");
//                        shuibeng1();
//                    }
//                    if( timestamp> (startTime + totleTime*1 + openTime)  && timestamp> (totleTime*2 + startTime )  ){
//                        shuibeng2();
//                        Log.d("dingshiqi","shuibengguan");
//                    }
//
//                    if( timestamp> (totleTime*2 + startTime )  && timestamp < (startTime + totleTime*2 + openTime) ){
//                        Log.d("dingshiqi","shuibengkai");
//                        shuibeng1();
//                    }
//                    if( timestamp> (startTime + totleTime*2 + openTime)  && timestamp> (totleTime*3 + startTime )  ){
//                        shuibeng2();
//                        Log.d("dingshiqi","shuibengguan");
//                    }

//                    for(int i = 0 ;i<result ;i++){
//                            if(timestamp> (totleTime*i + startTime ) && timestamp < (startTime + totleTime*i + openTime)){
//                                Log.d("dingshiqi","shuibengkai");
//                                shuibeng1();
//                            }else {
//                                shuibeng2();
//                                Log.d("dingshiqi","shuibengguan");
//                            }
//                    }

                }
            }
        };

        timerDingshi.schedule(taskDingshi, 5000, 2000);
//
        init();

        pinlv = (String) SpUtils.get(NoPlcActivity.this, "pin", "10");

        pm25 = (String) SpUtils.get(NoPlcActivity.this, "pm25", "100");
        tv_pm25.setText(pm25);

        tv_pinlv.setText(pinlv + "Hz");

        SetPinlvModbus(Integer.parseInt(pinlv));

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                Log.d("Handel", "" + msg.what);

                switch (msg.what) {
                    case 1:
                        if (dianjishort == 0) {

                            kaiguang.setText("喷淋水泵：关闭");
                            sendMqtt(mqtt_pub_topic, "shuibeng=0");
                        } else {
                            kaiguang.setText("喷淋水泵：开启");
                            sendMqtt(mqtt_pub_topic, "shuibeng=1");

                        }
                        if (famenshort == 0) {

                            shuifa.setText("进水阀门：关闭");
                            sendMqtt(mqtt_pub_topic, "famen=0");

                        } else {
                            shuifa.setText("进水阀门：开启");
                            sendMqtt(mqtt_pub_topic, "famen=1");

                        }


                        pb.setProgress((int) (yeweiF * 10));
                        tv_shuiwei.setText(df.format(yeweiF) + "米");
                        yeweishangchuan = "" + yeweiF;
                        break;
                }
                super.handleMessage(msg);
            }
        };
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //air=27.3=65.8=61.7=72=84=100.1=22.9
               // sendMqtt("bug", "air=28.7=65.8=61.7=72=84=100.1=22.9");
            }
        }, 5000);

    }

    //判断pm25
    private void PanDuanPm25() {

        if (moshi.equals("1")) {  //自动模式才判断
            if (toggleButton.isChecked()) {  //pm25 已经选中     本机设定值，比真实的数据大
                if (Integer.parseInt(pm25) < Integer.parseInt(p25)) {
                    shuibeng1();

                } else {
                    shuibeng2();
                }
            }
        }


    }
    //获取空气参数

    /**
     * private float wednu,zaoseng,p25,p10,qiya;
     * private float shidu,fengsu;
     */
    DecimalFormat df = new DecimalFormat("#.##");
    DecimalFormat df1 = new DecimalFormat("#.#");

    private void getShuiwei() {
        try {
            //获取液位  ID = 4   输入寄存器的值
            ReadInputRegistersRequest request1 = new ReadInputRegistersRequest(4, 0, 2);
            ReadInputRegistersResponse response1 = (ReadInputRegistersResponse) master.send(request1);
            if (response1.isException()) {
                Log.e("液位", "Exception response:" + response1.getExceptionMessage());
            } else {
                short[] list = response1.getShortData();
                yewei = list[0]; //电压值       0.001226    b= -0.65358
                Log.e("液位值电压值", yewei + "");

                if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
                    yeweiF = (float) (yewei * 0.00009375 - 0.375); //石家庄的


                } else {
                    yeweiF = (float) (yewei * 0.001226 - 0.65358);   //天津的

                }


                Log.e("液位", yeweiF + "==" + yewei);

                Message msg = Message.obtain();
                mHandler.sendEmptyMessage(1);

            }
        } catch (Exception ecc) {

        }

    }

    private void GetInfo() {
        //烟尘频闭状态上报
        sendMqtt(mqtt_pub_topic, "yanchen=" + (toggleButton.isChecked() ? "1" : "0"));

//        if (true) {
//            //获取立杆状态
//            try {
//                ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 9, 1);
//                ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master2.send(request);
//
////                ReadHoldingRegistersRequest request2 = new ReadHoldingRegistersRequest(3, 13, 1);
////                ReadHoldingRegistersResponse response2 = (ReadHoldingRegistersResponse) master2.send(request2);
//                if (response.isException()) {
//                    Log.e("SirPort1", "Exception response:_空气站" + response.getExceptionMessage());
//                } else {
//                    short[] list = response.getShortData();
//                    short getnum = list[0];
//                    gaodu =""+ getnum;
//                }
//
//
//                //new WriteMaskRegisterRequest()
//
//
//            } catch (Exception e) {
//                Log.e("Exception", e.getMessage());
//                try {
//                    master2.init();
//                } catch (ModbusInitException modbusInitException) {
//                    modbusInitException.printStackTrace();
//                }
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(NoPlcActivity.this, "获取立杆PLC失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        }

        //刷新保护值
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                tv_shuiweibaohu.setText("保护值：" + baohuzhi);
                //如果保护值比当前水位低，那么关闭水泵

                if (Float.parseFloat(baohuzhi) > Float.parseFloat(yeweishangchuan)) {
                    //关闭水泵 弹出土司
                    shuibeng2();
                    Toast.makeText(NoPlcActivity.this, "请补充液位", Toast.LENGTH_SHORT).show();

                }

                if ( 0.4f > Float.parseFloat(yeweishangchuan)) {
                    //比 0.4小，那么开始上水
                    famen1();
                    //Toast.makeText(NoPlcActivity.this, "请补充液位", Toast.LENGTH_SHORT).show();

                }
                if ( 1f < Float.parseFloat(yeweishangchuan)) {
                    //比 1.3大，那么开始关闭进水阀
                    famen2();
                    //Toast.makeText(NoPlcActivity.this, "请补充液位", Toast.LENGTH_SHORT).show();

                }


                tv_gaodu.setText("高度:"+gaodu+"(cm)");

//                if (shangshengStr == "1") {
//                    bnt_shenggao.setBackgroundColor(Color.RED);
//                } else {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        bnt_shenggao.setBackgroundColor(getColor(R.color.purple_500));
//                    }
//                }
//
//                if (xiajiangStr == "1") {
//                    btn_xiajiang.setBackgroundColor(Color.RED);
//                } else {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        btn_xiajiang.setBackgroundColor(getColor(R.color.purple_500));
//                    }
//                }
//                if (xuanzhuanStr == "1") {
//                    btn_xuanzhuan.setBackgroundColor(Color.RED);
//                } else {
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                        btn_xuanzhuan.setBackgroundColor(getColor(R.color.purple_500));
//                    }
//                }

            }

        });


        if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
            try {

                // 0 是水泵的状态
                ReadCoilsRequest request = new ReadCoilsRequest(5, 0, 2);
                ReadCoilsResponse response = (ReadCoilsResponse) master.send(request);
                if (response.isException()) {
                    Log.e("SirPort1", "Exception response:" + response.getExceptionMessage());
                } else {
                    boolean[] list = response.getBooleanData();

                    dianjishort = list[0] ? 1 : 0;
                    famenshort = list[1] ? 1 : 0;

                    Log.e("MOD", "电机状态1004" + dianjishort);
                }
            } catch (Exception e) {

                Log.e("SirPort3_gd2", e.getMessage());
            }

            // 二号站也从空气站读取
            try {

                // 空气站
                ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 500, 10);
                ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
                if (response.isException()) {
                    Log.e("SirPort1", "Exception response:_空气站" + response.getExceptionMessage());
                } else {
                    short[] list = response.getShortData();
                    wendu = df.format((double) list[5] / 10);
                    shidu = df.format((double) list[4] / 10);
                    zaoseng = df.format((double) list[6] / 10);
                    p25 = "" + list[7];
                    p10 = "" + list[8];
                    qiya = "" + df.format((double) list[9] / 10);
                    // fengsu = ""+list[0];
                    fengsu = "" + df.format((double) list[0] / 10);
                    ;
                }


//                //开启 水泵的 按钮就


            } catch (Exception e) {
                Log.e("Yewei", e.getMessage());
            }
        } else {

            try {

                // 0 是水泵的状态
                ReadCoilsRequest request = new ReadCoilsRequest(5, 0, 2);
                ReadCoilsResponse response = (ReadCoilsResponse) master.send(request);
                if (response.isException()) {
                    Log.e("SirPort1", "Exception response:" + response.getExceptionMessage());
                } else {
                    boolean[] list = response.getBooleanData();

                    dianjishort = list[0] ? 1 : 0;
                    famenshort = list[1] ? 1 : 0;

                    Log.e("MOD", "电机状态1004" + dianjishort);
                }
            } catch (Exception e) {

                Log.e("SirPort3", e.getMessage());
            }


            try {

                // 空气站
                ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 500, 10);
                ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
                if (response.isException()) {
                    Log.e("SirPort1", "Exception response:_空气站" + response.getExceptionMessage());
                } else {
                    short[] list = response.getShortData();
                    wendu = df.format((double) list[5] / 10);
                    shidu = df.format((double) list[4] / 10);
                    zaoseng = df.format((double) list[6] / 10);
                    p25 = "" + list[7];
                    p10 = "" + list[8];
                    qiya = "" + df.format((double) list[9] / 10);
                    // fengsu = ""+list[0];
                    fengsu = "" + df.format((double) list[0] / 10);
                    ;
                }


                //开启 水泵的 按钮就


            } catch (Exception e) {
                Log.e("Yewei", e.getMessage());
            }
        }


    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_pm25:  //设定pm25阈值
                setpm25();  //设定pm25阈值
                break;

            case R.id.btn_baohu:  //设置液位保护值
                ShezhiYeweiBaohu();  //设置液位保护值
                break;
//            case R.id.btn_qiehuan2:
//                //zidong2();
//                break;
//            case R.id.btn_qiehuan3:
//                //zidong3();
//                break;

            case R.id.btn_send1:
                famen1();
                break;
            case R.id.btn_send2:
                famen2();
                break;

            case R.id.btn_shuibeng1:
                if (moshi.equals("0")) {
                    shuibeng1();
                } else {
                    Toast.makeText(NoPlcActivity.this, "当前模式，不可以手动控制", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.btn_shuibeng2:

                shuibeng2();


                break;
//            btn_sheweishoudong = findViewById(R.id.btn_shoudong);
//            btn_sheweizidong = findViewById(R.id.btn_zidong);

            case R.id.btn_shoudong:
                //sheweishoudong(); //设为手动
                pinlv();  //设设置频率
                break;
            case R.id.btn_zidong:   //设为自动
                //sheweizidong();

                break;


        }
    }

    private void setpm25() {
        KeyBoardDialog keyBoardDialog = new KeyBoardDialog(this);
        keyBoardDialog.setOnClickKeyDialogListener(new KeyBoardDialog.KeyDialogOnClickListener() {
            @Override
            public void onPositiveClick(String password) {

                int pm25num = Integer.parseInt(password);
                pm25 = "" + pm25num;
                SpUtils.put(NoPlcActivity.this, "pm25", "" + pm25num);
                tv_pm25.setText(pm25);
                keyBoardDialog.cancel();
            }

            @Override
            public void onQuitClick() {
                //取消按钮回调

            }
        }).show();
    }
    private void ShezhiYeweiBaohu() {
        KeyBoardDialog keyBoardDialog = new KeyBoardDialog(this);
        keyBoardDialog.setOnClickKeyDialogListener(new KeyBoardDialog.KeyDialogOnClickListener() {
            @Override
            public void onPositiveClick(String password) {

                if ( ( Integer.parseInt(password) > 120 ) || (Integer.parseInt(password) <40)){
                    baohuzhi ="0.4";
                } else {
//                    gaodu =""+ getnum;
//
//                    double tt = ((double)getnum ) /100; //米
//                    Log.d("tttt",getnum+"=="+tt);
//                    sendMqtt(mqtt_pub_topic, "gaodu=" +   df.format(tt)+"米");
                    float fbaohu = Float.parseFloat(password)/100;
                    baohuzhi = df.format(fbaohu);
                    //sendMqtt(mqtt_pub_topic, "gaodu=" +   df.format(tt)+"米");

                }
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            sendMqtt(mqtt_pub_topic, "yeweibaohu="+baohuzhi);
                        } catch (Exception e) {
                            Log.e("Exception", e.getMessage());
                        }
                        super.run();

                    }
                }.start();

                keyBoardDialog.cancel();


//                //确认按钮回调
//                if (password.equals("666666")){
//
//                    keyBoardDialog.dismiss();
//                    startActivity(new Intent(MainActivity.this,SetUpActivity.class));
//                }else{
//                    Toast.makeText(MainActivity.this,"密码有误，请重新输入",Toast.LENGTH_SHORT).show();
//                }
            }

            @Override
            public void onQuitClick() {
                //取消按钮回调

            }
        }).show();

    }
    private void pinlv() {
        KeyBoardDialog keyBoardDialog = new KeyBoardDialog(this);
        keyBoardDialog.setOnClickKeyDialogListener(new KeyBoardDialog.KeyDialogOnClickListener() {
            @Override
            public void onPositiveClick(String password) {

                if (Integer.parseInt(password) > 50) {
                    tv_pinlv.setText("50Hz");

                } else {

                    SetPinlvModbus(Integer.parseInt(password));

                    tv_pinlv.setText(password + "Hz");
                    SpUtils.put(NoPlcActivity.this, "pin", password);
                }

                keyBoardDialog.cancel();


//                //确认按钮回调
//                if (password.equals("666666")){
//
//                    keyBoardDialog.dismiss();
//                    startActivity(new Intent(MainActivity.this,SetUpActivity.class));
//                }else{
//                    Toast.makeText(MainActivity.this,"密码有误，请重新输入",Toast.LENGTH_SHORT).show();
//                }
            }

            @Override
            public void onQuitClick() {
                //取消按钮回调

            }
        }).show();

    }

    private void famen1() {
//        if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
//
//            sendMqtt(mqtt_pub_topic, "famen=1");
//
//            return;
//        }
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.e("MingLing", "阀门开启");
                    // master.send(new WriteRegisterRequest(5,0,0));  //
                    master.send(new WriteCoilRequest(5, 1, true));


                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void famen2() {
//        if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
//
//            sendMqtt(mqtt_pub_topic, "famen=0");
//
//            return;
//        }
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.e("MingLing", "阀门关闭");
                    // master.send(new WriteRegisterRequest(5,0,0));  //
                    master.send(new WriteCoilRequest(5, 1, false));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void shuibeng2() {  //水泵关闭

        if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        sendMqtt(mqtt_pub_topic, "shuibeng=0");

                        master.send(new WriteRegisterRequest(2, 8192, 5));
                        //new WriteMaskRegisterRequest()


                    } catch (Exception e) {
                        Log.e("Exception", e.getMessage());
                    }
                    super.run();

                }
            }.start();

        } else {
            new Thread() {
                @Override
                public void run() {
                    try {
                        Log.e("MingLing", "水泵关闭");
                        // master.send(new WriteRegisterRequest(5,0,0));  //
                        master.send(new WriteCoilRequest(5, 0, false));


                    } catch (Exception e) {
                        Log.e("Exception", e.getMessage());
                    }
                    super.run();

                }
            }.start();
        }

    }

    private void shuibeng1() {  //水泵开启
        if (Float.parseFloat(baohuzhi) > Float.parseFloat(yeweishangchuan)) {
            //关闭水泵 弹出土司
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(NoPlcActivity.this, "水位太低，无法开启", Toast.LENGTH_SHORT).show();
                }
            });

            return;
        } else {
            //2号机器，那么这里用明空控制
            if (mqtt_sub_topic.equals("set_penlin_status_gd2")) {
                new Thread() {
                    @Override
                    public void run() {
                        try {

                            sendMqtt(mqtt_pub_topic, "shuibeng=1");
                            master.send(new WriteRegisterRequest(2, 8192, 1));
                            //new WriteMaskRegisterRequest()


                        } catch (Exception e) {
                            Log.e("Exception", e.getMessage());
                        }
                        super.run();

                    }
                }.start();

            } else {

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Log.e("MingLing", "水泵开启");
                            //  master.send(new WriteRegisterRequest(5,0,1));  //
                            master.send(new WriteCoilRequest(5, 0, true));


                        } catch (Exception e) {
                            Log.e("Exception", e.getMessage());
                        }
                        super.run();

                    }
                }.start();
            }

        }


    }

    private void SetPinlvModbus(int pinlv) {  //水泵开启
        new Thread() {
            @Override
            public void run() {
                try {


                    master.send(new WriteRegisterRequest(2, 4096, pinlv * 200));
                    //new WriteMaskRegisterRequest()


                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void initSirPort() {  //主机 计入的是 空气站 液位计， 变频器 本身用 ttyS6
        serialParameters = new SerialPortWrapperImpl("/dev/ttyS5", 9600, 8, 1, 0);
        modbusFactory = new ModbusFactory();
        master = modbusFactory.createRtuMaster(serialParameters);

        try {
            master.setTimeout(1000);
            master.setRetries(2);
            master.init();

            Log.e("SirPortmaster", " master.init()");


        } catch (ModbusInitException e) {


            e.printStackTrace();
        } finally {
            //master.destroy();
        }
        serialParameters2 = new SerialPortWrapperImpl("/dev/ttyS4", 9600, 8, 1, 0);
        modbusFactory2 = new ModbusFactory();
        master2 = modbusFactory2.createRtuMaster(serialParameters2);


        try {
            master2.setTimeout(3000);
            master2.setRetries(3);
            master2.init();

            Log.e("SirPortmaster", " master.init()");


        } catch (ModbusInitException e) {


            e.printStackTrace();
        } finally {
            //master.destroy();
        }

    }

    private String TAG = "mqtt";

    /**
     * 初始化
     */
    private void init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            startReconnect(options);

            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    Log.e(TAG, "连接丢失后connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    Log.d(TAG, "publish后会执行到这里deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    Log.d("MQTTavie", "subscribe后得到的消息会执行到这里面messageArrived----------" + topicName + "==" + message);
                    if (message.toString().equals("shuibeng=1")) {
                        if (moshi.equals("0")) {
                            shuibeng1();
                        } else {
                            Toast.makeText(NoPlcActivity.this, "当前模式，不可以手动控制", Toast.LENGTH_SHORT).show();
                        }

                    }
                    if (message.toString().equals("shuibeng=0")) {

                        shuibeng2();
                    }
                    if (message.toString().equals("famen=1")) {
                        famen1();

                    }
                    if (message.toString().equals("famen=0")) {

                        famen2();
                    }
                    if (message.toString().startsWith("yeweibaohu")) {
                        String[] arr = message.toString().split("=");
                        //SetPinlvModbus(Integer.parseInt(arr[1]));

                        baohuzhi = arr[1];

                    }
                    if (message.toString().startsWith("sudu=")) {
                        String[] arr = message.toString().split("=");
                        SetPinlvModbus(Integer.parseInt(arr[1]));

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_pinlv.setText(Integer.parseInt(arr[1]) + "Hz");
                                SpUtils.put(NoPlcActivity.this, "pin", "" + Integer.parseInt(arr[1]));
                            }
                        });
                    }
                    //策略   0 手动 1 自动  2 定时
                    if (message.toString().startsWith("celve=")) {
                        String[] arr = message.toString().split("=");
                        if (arr[1].equals("0")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    moshi = "0";
                                    tvMoshi.setText("喷淋策略：手动");
                                }
                            });

                        } else if (arr[1].equals("1")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    moshi = "1";
                                    tvMoshi.setText("喷淋策略：自动");
                                }
                            });
                        } else if (arr[1].equals("2")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    moshi = "2";
                                    tvMoshi.setText("喷淋策略：定时");
                                }
                            });
                        }
                    }
                    if (message.toString().startsWith("yanchen=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (arr[1].equals("1")) {
                                    toggleButton.setChecked(true);
                                } else {
                                    toggleButton.setChecked(false);
                                }
                            }
                        });
                    }

                    if (message.toString().startsWith("shangsheng=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ShengGaoLiGan();
                            }
                        });
                    }
                    if (message.toString().startsWith("xiajiang=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                JiangDiLiGan();
                            }
                        });
                    }

                    if (message.toString().startsWith("zanting=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                XuanZhuanLiGan();
                            }
                        });
                    }
                    if (message.toString().startsWith("zuozhuan=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YunTaiLeft();
                            }
                        });
                    }
                    if (message.toString().startsWith("youzhuan=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YunTaiRight();
                            }
                        });
                    }
                    if (message.toString().startsWith("fuwei=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YunTaiRecover();
                            }
                        });
                    }
                    if (message.toString().startsWith("tingzhi=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YunTaiStop();
                            }
                        });
                    }
                    if (message.toString().startsWith("shangzhuan=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                               YunTaiUp();
                            }
                        });
                    }
                    if (message.toString().startsWith("xiazhuan=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                YunTaiUp();
                            }
                        });
                    }

                    if (message.toString().startsWith("xuanzhuan=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                XuanZhuanLiGan();
                            }
                        });
                    }

                    if (message.toString().startsWith("shedingpm=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int pm25num = Integer.parseInt(arr[1]);
                                pm25 = "" + pm25num;
                                SpUtils.put(NoPlcActivity.this, "pm25", "" + pm25num);
                                tv_pm25.setText(pm25);
                            }
                        });
                    }
                    if (message.toString().startsWith("dingshicelve=")) {
                        //dingshicelve=09:08:00，10:09:00，5，6
                        String[] arr = message.toString().split("=");

                        String getTime = arr[1];  //09:08:00，10:09:00，5，6

                        String[] arr1 = getTime.split(",");  //  09:08:00，//10:09:00，//5//，6

                        String[] arr1Time = arr1[0].split(":");  //09 //08//00
                        String[] arr2Time = arr1[1].split(":");  //10//09//00

                        Calendar calendar = Calendar.getInstance();
                        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arr1Time[0])); // 设置小时
                        calendar.set(Calendar.MINUTE, Integer.parseInt(arr1Time[1]));     // 设置分钟
                        calendar.set(Calendar.SECOND, Integer.parseInt(arr1Time[2]));      // 设置秒
                        calendar.set(Calendar.MILLISECOND, 0); // 设置毫秒

                        // 如果需要获取今天的8:12，不需要设置年月日
                        // 如果需要获取特定日期的8:12，需要设置年月日字段

                        startTime = calendar.getTimeInMillis();

                        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arr2Time[0])); // 设置小时
                        calendar.set(Calendar.MINUTE, Integer.parseInt(arr2Time[1]));     // 设置分钟
                        calendar.set(Calendar.SECOND, Integer.parseInt(arr2Time[2]));      // 设置秒
                        calendar.set(Calendar.MILLISECOND, 0); // 设置毫秒


                        endTime = calendar.getTimeInMillis();

                        openTime = Integer.parseInt(arr1[2]) * 60 * 1000;
                        closeTime = Integer.parseInt(arr1[3]) * 60 * 1000;

                        Log.d("时间", startTime + "==" + endTime);

//                            runOnUiThread(new Runnable(){
//                                @Override
//                                public void run() {
//                                    int pm25num = Integer.parseInt(arr[1]);
//                                    pm25 = ""+pm25num;
//                                    SpUtils.put(NoPlcActivity.this,"pm25",""+pm25num);
//                                    tv_pm25.setText(pm25);
//                                }
//                            });
                    }


                    if (topicName.equals("bug") && mqtt_sub_topic.equals("set_penlin_status_gd2")) {


                        if (message.toString().startsWith("air=")) {
                            //air=30.3=65.8=61.7=72=84=100.1=22.9=1=1=1=1=1=1
                            String[] arr = message.toString().split("=");

                            wendu = arr[1];
                            shidu = arr[2];
                            zaoseng = arr[3];
                            p25 = arr[4];
                            p10 = arr[5];
                            qiya = arr[6];
                            fengsu = arr[7];
                            ;
                        }

                    }
                    //云台速度
                    if (message.toString().startsWith("yuntaisudu=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int pm25num = Integer.parseInt(arr[1]);
                                YunTaiSudu(pm25num);
                            }
                        });
                    }
                    //左限位
                    if (message.toString().startsWith("zuoxianwei=")) {

                        Log.d("限位", "1, 12,== "+message.toString());
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int pm25num = Integer.parseInt(arr[1]);
                                YunTaiLeftJiaodu(pm25num);
                            }
                        });

                    }
                    if (message.toString().startsWith("xunhang=1")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                KaiqiXunHuan();
                            }
                        });
                    }

                    if (message.toString().startsWith("xunhang=0")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                GuanbiXunHuan();
                            }
                        });
                    }

                    //右 限位
                    if (message.toString().startsWith("youxianwei=")) {
                        String[] arr = message.toString().split("=");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int pm25num = Integer.parseInt(arr[1]);
                                YunTaiRightJiaodu(pm25num);
                            }
                        });

                    }
                }


//                if (message.toString().equals("shangsheng=0")) {
//
//                    famen2();
//                }


            });
        } catch (Exception e) {
            e.printStackTrace();
        }


        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                    client.subscribe(mqtt_sub_topic);
                    client.subscribe(mqtt_sub_topic2);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();


    }

    // MQTT重新连接函数
    private void startReconnect(MqttConnectOptions options) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    mqttConnect(options);
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    // 订阅函数    (下发任务/命令)
    public void publishmessageplus(String topic, String message2) {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic, message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }

    // MQTT连接函数
    private void mqttConnect(MqttConnectOptions options) {
        new Thread(() -> {
            try {
                if (!(client.isConnected()))  //如果还未连接
                {
                    client.connect(options);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    //发送空气参数
    private void SendAir() {


        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                //tv_air.setText("空气参数：" + "温度:" + wendu + "，湿度:" + shidu + "，噪声:" + zaoseng + "，PM2.5:" + p25 + "，PM10:" + p10 + "，气压:" + qiya + "，风速:" + fengsu);

                // TvWndu,Tv_shidu,TV_p25,TV_p10,TV_zaosheng,tv_qiya,TV_fengsu;
                TvWndu.setText(wendu);
                Tv_shidu.setText(shidu);
                TV_zaosheng.setText(zaoseng);
                TV_p25.setText(p25);
                TV_p10.setText(p10);
                tv_qiya.setText(qiya);
                TV_fengsu.setText(fengsu);

                sendMqtt(mqtt_pub_topic, "air=" + wendu + "," + shidu + "," + zaoseng + "," + p25 + "," + p10 + "," + qiya + "," + fengsu + "," + dateFormat.format(new Date()));
                sendMqtt(mqtt_pub_topic, "yewei=" + yeweishangchuan);

                sendMqtt(mqtt_pub_topic, "xuanzhuan=" + xuanzhuanStr);
                sendMqtt(mqtt_pub_topic, "xiajiang=" + xiajiangStr);
                sendMqtt(mqtt_pub_topic, "shangsheng=" + shangshengStr);

            }

        });
    }

    private void sendMqtt(String topic, String meg) {
        if (client != null && client.isConnected()) {

            MqttMessage message = new MqttMessage();
            message.setPayload(meg.getBytes());
            try {
                client.publish(topic, message);

                Log.d("SendMqtt", meg);
            } catch (MqttException e) {
                e.printStackTrace();
            }

        }

    }

    public void zuozhuang(View view) {
        XuanZhuanLiGan();
    }

    public void youzhuan(View view) {

    }

    public void jiangdi(View view) {
        JiangDiLiGan();
    }

    //升高的点击
    public void shengao(View view) {
        ShengGaoLiGan();
    }

    //设置手动
    public void SheShoudong(View view) {
        moshi = "0";
        tvMoshi.setText("喷淋策略：手动");
    }

    //设置自动
    public void Shezidong(View view) {
        moshi = "1";
        tvMoshi.setText("喷淋策略：自动");
    }

    //设置定时
    public void Shedingshi(View view) {
        moshi = "2";
        tvMoshi.setText("喷淋策略：定时");
    }

    //升高命令
    private void ShengGaoLiGan() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    //master2.send(new WriteRegisterRequest(1, 2, 1));
                    master2.send(new WriteRegisterRequest(1, 0, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void JiangDiLiGan() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    //master2.send(new WriteRegisterRequest(1, 2, 1));
                    master2.send(new WriteRegisterRequest(1, 1, 1));

                }

                    //new WriteMaskRegisterRequest()


                 catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void XuanZhuanLiGan() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    master2.send(new WriteRegisterRequest(1, 2, 1));


                    //new WriteMaskRegisterRequest()


                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 上转
    private void YunTaiUp() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 5, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 下
    private void YunTaiDown() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 6, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 左
    private void YunTaiLeft() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 3, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 右
    private void YunTaiRight() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 4, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 停止
    private void YunTaiStop() {

        new Thread() {
            @Override
            public void run() {
                try {
                    master2.send(new WriteRegisterRequest(1, 7, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 复位
    private void YunTaiRecover() {

        new Thread() {
            @Override
            public void run() {
                try {

                    master2.send(new WriteRegisterRequest(1, 8, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    //云台 速度设置
    private void YunTaiSudu(int sudu) {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    master2.send(new WriteRegisterRequest(1, 14, sudu));
                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }
    //云台 速度设置
    private void YunTaiLeftJiaodu(int zuojiao) {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    master2.send(new WriteRegisterRequest(1, 12, zuojiao));
                    Log.d("限位", "1, 12,== "+zuojiao);
                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }
    //云台 右边的角度
    private void YunTaiRightJiaodu(int youjiaodu) {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升
                    master2.send(new WriteRegisterRequest(1, 13, youjiaodu));

                    Log.d("限位", "1, 13,== "+youjiaodu);
                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    public void kaiqixunhang(View view) {
        KaiqiXunHuan();}
    public void yuntaizuozhuang(View view) {
        GuanbiXunHuan();
    }


    public void guanbixunhang(View view) {
        YunTaiLeft();
    }
    public void yuntaiyou(View view) {
        YunTaiRight();
    }

    public void yuntaishang(View view) {
        YunTaiUp();
    }

    public void yuntaixia(View view) {
        YunTaiDown();
    }

    public void yuntaiting(View view) {
        YunTaiStop();
    }

    public void yuntaifuwei(View view) {
        YunTaiRecover();
    }


    private void GuanbiXunHuan() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 11, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

    private void KaiqiXunHuan() {

        new Thread() {
            @Override
            public void run() {
                try {
                    //先停止  在上升

                    master2.send(new WriteRegisterRequest(1, 10, 1));

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage());
                }
                super.run();

            }
        }.start();
    }

}